package com.fount4j.generator.util;

import com.fount4j.generator.constant.GeneratorConstants;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 生成文件的工具类
 *
 * @author Morven 2016/12/22
 */
public final class GeneratorFileUtils {
    private static final Logger LOGGER = LoggerFactory.getLogger(GeneratorFileUtils.class);

    private GeneratorFileUtils() {}

    /**
     * 根据配置的根路径以及包路径和文件名，创建要生成的文件对象
     *
     * @param resourcePath 文件目录
     * @param packageName  文件包目录
     * @param fileName     文件名
     * @return 目标文件对象
     */
    public static File getFile(String resourcePath, String packageName, String fileName) {
        File path;
        if (StringUtils.isBlank(resourcePath)) {
            path = new File(PathUtils.getProjectDir());
        } else if (resourcePath.startsWith("file:")) {
            path = new File(resourcePath.replaceFirst("file:", ""));
        } else {
            path = new File(PathUtils.getProjectDir(), resourcePath);
        }
        if (StringUtils.isNotBlank(packageName)) {
            String packageDir = packageName.replace('.', File.separatorChar);
            path = new File(path, packageDir);
        }
        path = new File(path, fileName);
        return path;
    }

    /**
     * 读取文件中的自定义内容
     *
     * @param file 目标文件
     * @return 自定义内容
     */
    public static String getCustomContent(File file) {
        if (!file.exists()) {
            return null;
        }
        try {
            String content = FileUtils.readFileToString(file, GeneratorConstants.GLOBAL_ENCODING);
            int startIndex = content.indexOf("<custom>");
            int endIndex = content.indexOf("</custom>");
            if (startIndex > -1 && endIndex > startIndex) {
                Pattern pattern = Pattern.compile(".*<custom>(.*\\r\\n*.*)*</custom>.*");
                Matcher matcher = pattern.matcher(content);

                if (matcher.find()) {
                    return matcher.group(0);
                }
            }
        } catch (IOException e) {
            LOGGER.error("读取文件中的自定义内容出错", e);
        }
        return null;
    }
}
